package com.demo.htmltopng.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;

/**
 * @author luzck
 * @since 2022/6/29
 */
@Slf4j
public class CustomWKHtmlToPdfUtil {

    //wkhtmltopdf在系统中的路径
    private static final String toImgTool = "D:\\dev\\develop\\wkhtmltopdf\\bin\\wkhtmltoimage.exe";

    public String getCommand(String sourceFilePath, String targetFilePath) {
        String system = System.getProperty("os.name");

        if(system.contains("Windows")) {
            return toImgTool + " " + sourceFilePath + " " + targetFilePath;
        } else if(system.contains("Linux")) {
            //return "docker exec -it wkhtmltopdf wkhtmltoimage " + sourceFilePath + " " + targetFilePath;
            return "wkhtmltox_http";
        }
        return "";
    }

    public static void run(String htmlPath, String imagePath, String wkhtmltox_path) throws IOException {
        CustomWKHtmlToPdfUtil util = new CustomWKHtmlToPdfUtil();
        String commands = util.getCommand(htmlPath, imagePath);

        // Linux上采用http调用方式
        if ("wkhtmltox_http".equals(commands)) {
            Map<String, String> data = new HashMap<>();
            data.put("command", "wkhtmltoimage " + htmlPath + " " + imagePath);
            String result = HttpClientUtils.doPost(wkhtmltox_path, data);
            log.info("------wkhtmltox_http响应结果：{}", result);
            return;
        }
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(commands);
            int i = process.waitFor();//这个调用比较关键，就是等当前命令执行完成后再往下执行
            log.info("------执行{}，执行命令：{}", (i == 0 ? "成功":"失败"), commands);
        } catch (Exception e) {
            e.printStackTrace();
            //"使用wkhtmltopdf出错:" + e.getMessage();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }

    public static File toLocalHtmlFile(String readyParsedTemplate) {
        String path = System.getProperty("user.dir") + File.separator + "tmp" + File.separator + "wkhtmltopdf";
        String fileName = UUID.randomUUID().toString();
        File file = new File(path + File.separator + fileName + ".html");
        File pathFile = new File(path);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        String absolutePath = file.getAbsolutePath();
        try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(absolutePath, true)))) {

            out.write(readyParsedTemplate);
            // 把缓存区内容压入文件
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 最后记得关闭文件
        return file;
    }

}
